package com.bencordingley.remotecontrol;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

public class Updater extends Activity {

	private DefaultHttpClient client;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Toast.makeText(this, "Checking for updates", Toast.LENGTH_SHORT).show();
		int newestVersion = getNewestVersion("http://www.bencordingley.com/update/RemoteControl/client");
		int currentVersion = getCurrentVersion(getPackageName());
		if (newestVersion > currentVersion) {
			Toast.makeText(this, "Downloading update", Toast.LENGTH_SHORT).show();
			File update = downloadFile("http://www.bencordingley.com/RemoteControl.apk");
			if (update != null) {
				startActivity(new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(update), "application/vnd.android.package-archive"));
			}
		}
		finish();
	}

	private File downloadFile(String packageUrl) {
		DefaultHttpClient c = getClient();
		HttpGet request = new HttpGet(packageUrl);
		HttpResponse resp = null;
		String fileName = null;
		try {
			fileName = new URL(packageUrl).getFile();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		File file = null;
		try {
			file = File.createTempFile(fileName, null);
			resp = c.execute(request);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (resp != null && file != null) {
			HttpEntity enty = resp.getEntity();
			if (enty != null) {
				try {
					byte[] buf = new byte[1024];
					int numRead = 0;
					BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
					InputStream in = enty.getContent();
					while ((numRead = in.read(buf)) != -1) {
						out.write(buf, 0, numRead);
					}
					out.close();
					in.close();
				} catch (IOException ex) {
					file = null;
					ex.printStackTrace();
				}
				try {
					enty.consumeContent();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			file = null;
		}
		return file;
	}

	private int getNewestVersion(String updateUrl) {
		DefaultHttpClient c = getClient();
		HttpGet request = new HttpGet(updateUrl);
		HttpResponse resp = null;
		int version = 0;
		try {
			resp = c.execute(request);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (resp != null) {
			HttpEntity enty = resp.getEntity();
			if (enty != null) {
				String content = null;
				try {
					content = streamToString(enty.getContent());
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (content != null) {
					try {
						version = Integer.parseInt(content);
					} catch (NumberFormatException ex) {

					}
				}
				try {
					enty.consumeContent();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return version;
	}

	private DefaultHttpClient getClient() {
		if (client == null) {
			client = new DefaultHttpClient();
		}
		return client;
	}

	public int getCurrentVersion(String packageName) {
		PackageManager packageManager = getPackageManager();
		PackageInfo info = null;
		int version = 0;
		try {
			info = packageManager.getPackageInfo(packageName, 0);
		} catch (NameNotFoundException e) {
			Toast.makeText(this, "Package not found", Toast.LENGTH_LONG);
			e.printStackTrace();
		}
		if (info != null) {
			version = info.versionCode;
		}
		return version;
	}

	public static String streamToString(InputStream is) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		return sb.toString();
	}
}